package com.example.project7;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

public class MineFragment extends Fragment {

    private TextView tvUserEmail;
    private TextView tvCurrentInterest;
    private Button btnSelectInterest;
    private Button btnLogout;
    private SharedViewModel sharedViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mine, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化视图
        tvUserEmail = view.findViewById(R.id.tv_user_email);
        tvCurrentInterest = view.findViewById(R.id.tv_current_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnLogout = view.findViewById(R.id.btn_logout);

        // 获取 ViewModel 实例
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

        // 观察并更新 UI
        sharedViewModel.getUserEmail().observe(getViewLifecycleOwner(), email -> {
            tvUserEmail.setText("用户邮箱: " + (email != null ? email : "未登录"));
        });

        sharedViewModel.getCurrentInterest().observe(getViewLifecycleOwner(), interest -> {
            tvCurrentInterest.setText("当前兴趣: " + interest);
        });

        // 设置点击事件
        btnSelectInterest.setOnClickListener(v -> showInterestDialog());
        btnLogout.setOnClickListener(v -> sharedViewModel.logout());
    }

    private void showInterestDialog() {
        // 兴趣列表
        final String[] interests = {"编程", "音乐", "旅行", "美食", "健身"};

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("请选择您的兴趣");
        builder.setItems(interests, (dialog, which) -> {
            // "which" 参数是用户点击的选项的索引
            String selectedInterest = interests[which];
            // 更新 ViewModel 中的数据
            sharedViewModel.setCurrentInterest(selectedInterest);
        });
        builder.show();
    }
}